from decorator import decorator
import random
import string

import pylons.decorators


def filter_dict(dic, keys):
  """Returns a new dictionary {k: v} with k from keys and v from dic[k].
  If a key k is in keys and not in dic, raises KeyError.
  
  Arguments:
    - dic: dict.
    - keys: list of strings.
  """
  return dict([(k, dic[k]) for k in keys])


@decorator
def ajax_validator(f, *args, **kwargs):
  """If the function raise an error, returns json false, otherwise true.
  """
  try:
    f(*args, **kwargs)
    return True
  except Exception, e:
    return False


#TODO: to test
@decorator
def set_trace_d(f, *args, **kwargs):
  """pdb.set_trace() right before the function.
  """
  import pdb
  pdb.set_trace()
  res = f(*args, **kwargs)
  return res


RANDOM_ALPHABET = string.ascii_letters + string.digits
def get_random_string(length):
  """Returns a random string having length chars.
  
  Arguments:
    - length: the length of the string
  """
  return ''.join([random.choice(RANDOM_ALPHABET) for i in xrange(length)])
  